package com.security.springsecurity01.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Controller
@RequestMapping("/user")
public class LoginContaroller {


    @RequestMapping("/showLogin")
    public String showLogin(){
        System.out.println("进入登录页面...");
        return "login";
    }


    @RequestMapping("/login")
    public String login(){
        System.out.println("用户登录...");
        return "login";
    }

    @RequestMapping("/toSuc")
    public String main(){
        System.out.println("认证成功...");
        return "redirect:/main.html";
    }

    @RequestMapping("/toError")
    public String error(){
        System.out.println("认证失败...");
        return "redirect:/error.html";
    }
    @RequestMapping("/invdate")
    public String invdate(){
        System.out.println("回话超时...");
        return "invdate";
    }
    @RequestMapping("/getUser")
    public String getUsername(){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(!authentication.isAuthenticated()){
            return "redirect:/error.html";
        }
        Object userdetail = authentication.getPrincipal();
        if(userdetail instanceof UserDetails){
            System.out.println("获取认证的用户="+((UserDetails)userdetail).getUsername());
            return ((UserDetails)userdetail).getUsername();
        }
        return "";

    }


}
